<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Promo extends ORM
{
    //1单图单地址 2多图多地址 3优惠券 4视频
    public static $type = [
        1 => '单图固定广告',
        2 => '多图轮播广告',
        3 => '优惠券',
        4 => '视频广告',
    ];

    public static function promo_list($params)
    {
        $model = DB::select()->from('promo')->where('id', '>', '0');
        if (!empty($params['keyword'])) {
            $model->and_where('title', 'like', '%' . $params['keyword'] . '%');
        }
        if ($params['start_date']) {
            $model->and_where('start_date', '>=', strtotime($params['start_date']));
        }
        if ($params['end_date']) {
            $model->and_where('end_date', '<=', strtotime($params['end_date']));
        }
        if ($params['type']) {
            $model->and_where('type', '=', $params['type']);
        }
        if ($params['status']) {
            $time = time();
            switch ($params['status']) {
                case 1:
                    $model->and_where('start_date', '>', $time);
                    break;
                case 2:
                    $model->and_where('start_date', '<', $time);
                    $model->and_where('end_date', '>', $time);
                    break;
                case 3:
                    $model->and_where('end_date', '<', $time);
                    break;
            }
        }

        $total = $model->execute()->count();
        $model->order_by(DB::expr(" modtime DESC,addtime DESC,start_date ASC"));
        $model->offset($params['start']);
        $model->limit($params['limit']);
        $list = $model->execute()->as_array();

        foreach ($list as &$v) {
            $v['status_name'] = $v['start_date'] > time() ? '未开始' : ($v['end_date'] < time() ? '已结束' : '进行中');
            $v['start_date'] = $v['start_date']?date('Y-m-d', $v['start_date']):'--';
            $v['end_date']   = $v['end_date']?date('Y-m-d', $v['end_date']):'--';
            $v['type_name']  = self::$type[$v['type']];
            $click_info      = DB::select()->from('promo_click')->where('promo_id', '=', $v['id'])->execute()->as_array();
            if ($click_info) {
                $v['click_peo_num'] = count($click_info);
                $v['click_num']     = array_sum(array_column($click_info, 'number'));
            } else {
                $v['click_peo_num'] = 0;
                $v['click_num']     = 0;
            }
        }

        return [
            'total'   => $total,
            'lists'   => $list,
            'success' => true
        ];
    }

    public static function get_coupon_list($params)
    {
        $time  = time();
        $model = DB::select('id', 'name', 'starttime', 'endtime', 'totalnumber')
            ->from('coupon')
            ->where('isdel', '=', '0')
            ->and_where('usage_scenario', '=', 0)
            ->and_where(DB::expr(" and (isnever=0 or (isnever=1 and endtime>{$time})) "));
        if ($params['keyword']) {
            $model->and_where(DB::expr(" AND name LIKE '%{$params['keyword']}%' "));
        }
        if ($params['coupon_id']) {
            $model->and_where(DB::expr(" AND id NOT IN({$params['coupon_id']}) "));
        }
        $total = $model->execute()->count();
        $model->order_by('id', 'desc');
        $model->offset($params['start'])->limit($params['limit']);
        $coupon_list = $model->execute()->as_array();

        foreach ($coupon_list as &$v) {
            if ($v['starttime']) {
                $start_date           = date('Y-m-d', $v['starttime']);
                $end_date             = date('Y-m-d', $v['endtime']);
                $v['validity_period'] = $start_date . ' 至 ' . $end_date;
            } else {
                $v['validity_period'] = '永久有效';
            }
        }

        return [
            'total'   => $total,
            'lists'   => $coupon_list,
            'success' => true
        ];
    }

    public static function promo_handle($params,$promo_id)
    {
        $model = ORM::factory('promo');
        if($promo_id){
            $model->where('id', '=', $promo_id);
            $model->find();
            $model->modtime = time();
        }else{
            $model->addtime = time();
        }
        foreach ($params as $k=>$v) {
            $model->$k = $v;
        }
        $model->save();
        if ($model->saved()) {
            $model->reload();

            return [
                'status' => true,
                'id'     => $model->id,
            ];
        } else {
            return [
                'status' => false,
            ];
        }
    }

    public static function promo_detail($id)
    {
        $info               = DB::select()->from('promo')->where('id', '=', $id)->execute()->current();
        $info['start_date'] = date('Y-m-d', $info['start_date']);
        $info['end_date']   = date('Y-m-d', $info['end_date']);
        $piclist            = explode(',', $info['piclist']);
        $info['img_url']    = explode('||', $piclist[0]);
        $jump_url           = explode('||', $piclist[1]);
        $arr                = [];
        foreach ($jump_url as $k => $v) {
            $arr[$k]['url_code'] = $v;
            $arr[$k]['data'] = json_decode(urldecode($v), true);
        }
        $info['jump_url']  = $arr;
        $info['page_link'] = self::get_page_link($info['page_link']);
        if($info['coupon_id']){
            $info['coupon_list'] = DB::select()->from('coupon')->where('id','in',explode(',',$info['coupon_id']))->execute()->as_array();
            foreach ($info['coupon_list'] as &$v) {
                if ($v['starttime']) {
                    $start_date           = date('Y-m-d', $v['starttime']);
                    $end_date             = date('Y-m-d', $v['endtime']);
                    $v['validity_period'] = $start_date . ' 至 ' . $end_date;
                } else {
                    $v['validity_period'] = '永久有效';
                }
            }
        }

        return $info;
    }

    public static function get_page_link($page_link)
    {
        $page_link  = json_decode($page_link,true);
        $page_all   = Kohana::$config->load('uniapp')->get('nav');
        $model_page = $page_all['model_page'];
        $page_list  = [];
        $status     = 1;
        foreach ($model_page as $v) {
            if (in_array('/pages/index/home', $page_link) && $status) {
                $page_list[]  =  [
                    'name'    => '首页',
                    'type_id' => 0,
                    'path'    => '/pages/index/home',
                    'title'   => 'UNI端首页',
                ];
                $status = 0;
            }
            if (in_array($v['page'][0]['path'], $page_link)) {
                $type_name               = DB::select()->from('model')->where('id', '=', $v['typeid'])->execute()->get('modulename');
                $v['page'][0]['name']    = $type_name;
                $v['page'][0]['type_id'] = $v['typeid'];
                $page_list[]             = $v['page'][0];
            }
            if (in_array($v['page'][1]['path'], $page_link)) {
                $v['page'][1]['name']    = $type_name;
                $v['page'][1]['type_id'] = $v['typeid'];
                $page_list[]             = $v['page'][1];
            }
        }

        return $page_list;
    }

    public static function promo_automatic_delisting()
    {
        $promo = DB::select()->from('promo')
            ->where('is_open', '=', 1)
            ->and_where('end_date','<',strtotime(date('Ymd')))
            ->execute()->as_array();
        foreach ($promo as $v) {
            DB::update('promo')->set(['is_open'=>0])->where('id', '=', $v['id'])->execute();
        }
    }
}